package com.shxc.smarttrade.old.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapter.ViewPagerAdapter;
import com.shxc.smarttrade.old.bean.AlphaBaseInfo;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.foreignfragment.AlphaDataFragment;
import com.shxc.smarttrade.old.foreignfragment.AlphaHistoryFragment;
import com.shxc.smarttrade.old.foreignfragment.AlphaPositionFragment;
import com.shxc.smarttrade.old.myview.CommonDialog;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/11/8.
 */

public class AlphaActivity extends FragmentActivity {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_broker)
    TextView tvBroker;
    @BindView(R.id.btn_subscribe)
    Button btnSubscribe;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    private static final String[] tabName = {"数据", "持仓", "历史"};
    private List<String> mDataList = Arrays.asList(tabName);
    private int userId = -1;
    private boolean isSub = false;
    private String accessToken = "";
    private int eaId = -1;
    private AlphaDataFragment mAlphaDataFragment;
    private MyProgressDialog shortDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alpha);
        CloseAllActivity.getScreenManager().pushActivity(this);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        tvCenter.setText("智能策略");
        userId = SpUtils.getInt(this, "userId", -1);
        accessToken = SpUtils.getString(getApplicationContext(), "accessToken", "");
        eaId = getIntent().getIntExtra("eaId", -1);
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(mAlphaDataFragment = new AlphaDataFragment());
        fragmentList.add(new AlphaPositionFragment());
        fragmentList.add(new AlphaHistoryFragment());

        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), fragmentList));
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setScrollPivotX(0.25f);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int i) {
                final SimplePagerTitleView clipPagerTitleView = new SimplePagerTitleView(context);
                clipPagerTitleView.setText(mDataList.get(i));
                clipPagerTitleView.setNormalColor(Color.parseColor("#999999"));
                clipPagerTitleView.setSelectedColor(Color.parseColor("#36436a"));
//                clipPagerTitleView.setTextSize(BaseUtils.dip2px(context, 5.2f));
                clipPagerTitleView.setPadding(BaseUtils.dip2px(context, 16.0f), 0, BaseUtils.dip2px(context, 16.0f), 0);

                clipPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(i);
                    }
                });

                return clipPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(new Integer[]{Color.parseColor("#36436a")});
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(BaseUtils.dip2px(context, 2));
                indicator.setLineWidth(BaseUtils.dip2px(context, 60));
                indicator.setRoundRadius(2);
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
//                indicator.setYOffset(UIUtil.dip2px(context, 39));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
//        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
//        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
////        titleContainer.setDividerPadding(UIUtil.dip2px(getActivity(), 1));
//        titleContainer.setDividerDrawable(getResources().getDrawable(R.drawable.simple_splitter));
        ViewPagerHelper.bind(magicIndicator, viewPager);
    }

    @OnClick({R.id.rl_left, R.id.btn_subscribe})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.btn_subscribe:
//                BaseUtils.showToast("敬请期待", this);

                if (userId != -1) {
                    if (isSub)
                        showAlertDialog(isSub, "是否取消订阅智能EA");
                    else
                        showAlertDialog(isSub, "是否订阅智能EA");

                } else {
                    BaseUtils.showToast("未登录无法订阅", this);
                }

                break;
        }
    }

    private void showAlertDialog(final boolean tag, String text) {
        CommonDialog commonDialog = new CommonDialog(this, R.style.customDialogStyle);
        commonDialog.setCanceledOnTouchOutside(true);
        commonDialog.setBaseText("提示", text, "取消", "确定");
        commonDialog.setYesCLickRunAble(new Runnable() {
            @Override
            public void run() {
                if (tag) {//取消订阅
                    dealAlpha();
                } else {//订阅
                    subAlpha();
                }
            }
        });
        commonDialog.show();
    }

    public void setBaseData(AlphaBaseInfo.DataBean db) {
        AlphaBaseInfo.DataBean.EaInfoBean eb = db.getEaInfo();

        if (eb != null) {
            tvVersion.setText("版本：" + eb.getVersion());
            tvDate.setText("更新时间：" + BaseUtils.getDateFromMillionSeconds(eb.getUpdateAt(), "yyyy-MM-dd"));
            if (eb.getBrokerType().equals("1"))
                tvBroker.setText("经纪商：TigerWit");
            isSub = db.getIsSub();
            if (isSub)
                btnSubscribe.setText("取消订阅");
            else
                btnSubscribe.setText("立即订阅");

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CloseAllActivity.getScreenManager().popActivity(this);
    }


    public void showDialog() {
        if (shortDialog == null) {
            shortDialog = new MyProgressDialog(this);
            shortDialog.setCancelable(false);
        }
        shortDialog.show();
    }

    public void dissDialog() {
        if (shortDialog != null)
            shortDialog.dismiss();
    }

    /**
     * 订阅
     */
    private void subAlpha() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", String.valueOf(userId));
        map.put("accessToken", accessToken);
        map.put("eaId", String.valueOf(eaId));
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.ALPHA_SUB_EA, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                BaseUtils.showToast("网络异常", AlphaActivity.this);
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject json = new JsonParser().parse(response).getAsJsonObject();
                    if (json.get("err_code").getAsString().equals("0")) {
                        BaseUtils.showToast("订阅成功", AlphaActivity.this);
                        if (mAlphaDataFragment != null) {
                            mAlphaDataFragment.initData();
                        }
                    } else {
                        BaseUtils.showToast(json.get("err_msg").getAsString(), AlphaActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 取消订阅
     */
    private void dealAlpha() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", String.valueOf(userId));
        map.put("accessToken", accessToken);
        map.put("eaId", String.valueOf(eaId));
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.ALPHA_DEAL_EA, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                BaseUtils.showToast("网络异常", AlphaActivity.this);
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject json = new JsonParser().parse(response).getAsJsonObject();
                    if (json.get("err_code").getAsString().equals("0")) {
                        BaseUtils.showToast("取消成功", AlphaActivity.this);
                        if (mAlphaDataFragment != null) {
                            mAlphaDataFragment.initData();
                        }
                    } else {
                        BaseUtils.showToast(json.get("err_msg").getAsString(), AlphaActivity.this);
                    }
                }
            }
        });
    }
}
